<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\model\Distribution as ModelDistribution;
use fast\Tree;
use PDOException;
use think\Db;
use think\exception\ValidateException;

/**
 * 配送方式
 *
 * @icon fa fa-circle-o
 */
class Distribution extends Backend
{

    /**
     * Distribution模型对象
     * @var \app\common\model\Distribution
     */
    protected $model = null;
    protected $categorylist = [];
    protected $acctLimit = true;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Distribution;
        $this->categorylist = collection($this->model->where('acct_id', $this->auth->acct_id)->order('weigh desc,id desc')->select())->toArray();
        $tree = Tree::instance();
        $tree->init($this->categorylist, 'pid');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'title');
        $list = $this->model->where('pid',  0)->where('acct_id', $this->auth->acct_id)->select();
        $this->view->assign('list', $list);
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $search = $this->request->request("search");
            $type = $this->request->request("type");

            //构造父类select列表选项数据
            $list = [];

            foreach ($this->categorylist as $k => $v) {
                if ($v['pid'] > 0) {
                    $this->categorylist[$k]['prant'] = (new \app\common\model\Distribution)->get($v['pid'])->toArray();
                } else {
                    $this->categorylist[$k]['prant'] = [];
                }
                if ($search) {
                    if ($v['type'] == $type && stripos($v['title'], $search) !== false) {
                        if ($type == "all" || $type == null) {
                            $list = $this->categorylist;
                        } else {
                            $list[] = $v;
                        }
                    }
                } else {
                    if ($type == "all" || $type == null) {
                        $list = $this->categorylist;
                    } elseif ($v['type'] == $type) {
                        $list[] = $v;
                    }
                }
            }

            $total = count($list);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $child = ModelDistribution::get(['pid' => $item->id]);
                if ($child) {
                    exception('请先删除下级分类');
                    break;
                }
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException | \Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
}
